package com.feib.soeasy.dao.hibernate;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.feib.soeasy.dao.PayerTempDao;
import com.feib.soeasy.model.PayerTemp;
import com.feib.soeasy.model.UploadFile;
import com.feib.soeasy.pagination.PaginatedList;

/**
 * @title (#)PayerTempHibernateDao.java<br>
 * @description <br>
 * @author Anson Tsai<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2011/2/12 create by Anson Tsai<br>
 */
@Repository("payerTempDao")
public class PayerTempHibernateDao extends BaseHibernateDao<PayerTemp, Long> implements PayerTempDao {

    @Override
    @SuppressWarnings("unchecked")
    public List<PayerTemp> getPayerTempNoConfirm(String groupNo, String payerNo) {
        DetachedCriteria criteria = DetachedCriteria.forClass(this.getPersistentClass());
        criteria.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY);

        if (StringUtils.isNotBlank(groupNo)) {
            DetachedCriteria groupCriteria = criteria.createCriteria("group");
            groupCriteria.add(Restrictions.eq("groupNo", groupNo));
        }

        if (StringUtils.isNotBlank(payerNo)) {
            criteria.add(Restrictions.eq("payerNo", payerNo));
        }

        criteria.add(Restrictions.isNull("payerStatus"));

        return this.getHibernateTemplate().findByCriteria(criteria);
    }

    @Override
    @SuppressWarnings("unchecked")
    public PaginatedList<PayerTemp> getPayerTempNoConfirm(PaginatedList<PayerTemp> paginationConfig) {
        PaginatedList<PayerTemp> result = new PaginatedList<PayerTemp>();
        result.setPageSize(paginationConfig.getPageSize());
        result.setPageNumber(paginationConfig.getPageNumber());
        result.setSortCriterion(paginationConfig.getSortCriterion());
        result.setSortDirection(paginationConfig.getSortDirection());

        result.setFullListSize(super.countByDetachedCriteria(createDetachedCriteriaByConditions()));

        // 筆數大於0
        if (0 < result.getFullListSize()) {
            DetachedCriteria criteria = createDetachedCriteriaByConditions();

            // 排序
            if (null != paginationConfig.getSortCriterion()) {
                // 由小到大
                if (PaginatedList.SORT_DIRECTION_ASC == paginationConfig.getSortDirection()) {
                    criteria.addOrder(Order.asc(paginationConfig.getSortCriterion()));
                }
                else // 由大到小
                {
                    criteria.addOrder(Order.asc(paginationConfig.getSortCriterion()));
                }
            }

            int maxResults = result.getPageSize(); // the maximum number of
                                                   // results
            int firstResult = result.getFirstIndexForCurrentPage(); // the first
                                                                    // result to
                                                                    // retrieve,
                                                                    // numbered
                                                                    // from 0
            result.setPaginatedList(this.getHibernateTemplate().findByCriteria(criteria, firstResult, maxResults));
        }

        return result;
    }

    protected DetachedCriteria createDetachedCriteriaByConditions() {
        DetachedCriteria criteria = DetachedCriteria.forClass(this.getPersistentClass());
        criteria.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY);

        criteria.add(Restrictions.isNull("payerStatus"));
        criteria.add(Restrictions.isNull("uploadFile"));

        return criteria;
    }

    /* (non-Javadoc)
     * @see com.feib.soeasy.dao.PayerTempDao#findByUploadFilePk(java.lang.Long)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<PayerTemp> findByUploadFilePk(Long uploadFilePk) {
        DetachedCriteria criteria = DetachedCriteria.forClass(this.getPersistentClass());
        criteria.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY);
        DetachedCriteria uploadFileCriteria = criteria.createCriteria("uploadFile");
        uploadFileCriteria.add(Restrictions.idEq(uploadFilePk));
        return this.getHibernateTemplate().findByCriteria(criteria);
    }

    /* (non-Javadoc)
     * @see com.feib.soeasy.dao.PayerTempDao#deleteByUploadFilePk(java.lang.Long)
     */
    @Override
    public void deleteByUploadFilePk(Long uploadFilePk) {
        StringBuffer hql = new StringBuffer();
        hql.append("delete PayerTemp as p ");
        hql.append("where uploadFile = :uploadFile ");
        Query query = getSession().createQuery(hql.toString());
        UploadFile uploadFile = new UploadFile();
        uploadFile.setUploadFilePk(uploadFilePk);
        query.setParameter("uploadFile", uploadFile);
        query.executeUpdate();
    }

    /* (non-Javadoc)
     * @see com.feib.soeasy.dao.PayerTempDao#findByPayerTemp(com.feib.soeasy.model.PayerTemp, com.feib.soeasy.pagination.PaginatedList)
     */
    @SuppressWarnings("unchecked")
    @Override
    public PaginatedList<PayerTemp> findByPayerTemp(PayerTemp payerTemp, PaginatedList<PayerTemp> paginationConfig) {
        PaginatedList<PayerTemp> result = new PaginatedList<PayerTemp>();
        result.setPageSize(paginationConfig.getPageSize());
        result.setPageNumber(paginationConfig.getPageNumber());
        result.setSortCriterion(paginationConfig.getSortCriterion());
        result.setSortDirection(paginationConfig.getSortDirection());

        result.setFullListSize(super.countByDetachedCriteria(createDetachedCriteriaByPayerTemp(payerTemp)));

        // 筆數大於0
        if (0 < result.getFullListSize()) {
            DetachedCriteria criteria = createDetachedCriteriaByPayerTemp(payerTemp);

            // 排序
            if (null != paginationConfig.getSortCriterion()) {
                // 由小到大
                if (PaginatedList.SORT_DIRECTION_ASC == paginationConfig.getSortDirection()) {
                    criteria.addOrder(Order.asc(paginationConfig.getSortCriterion()));
                }
                else // 由大到小
                {
                    criteria.addOrder(Order.asc(paginationConfig.getSortCriterion()));
                }
            }

            int maxResults = result.getPageSize(); // the maximum number of
                                                   // results
            int firstResult = result.getFirstIndexForCurrentPage(); // the first
                                                                    // result to
                                                                    // retrieve,
                                                                    // numbered
                                                                    // from 0
            result.setPaginatedList(this.getHibernateTemplate().findByCriteria(criteria, firstResult, maxResults));
        }

        return result;
    }

    /**
     * @param payerTemp
     * @return
     */
    private DetachedCriteria createDetachedCriteriaByPayerTemp(PayerTemp entity) {
        
        DetachedCriteria criteria = DetachedCriteria.forClass(this.getPersistentClass());
        criteria.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY);
        
        Example example = Example.create(entity);
        example.enableLike(MatchMode.START);
        example.excludeZeroes();
        criteria.add(example);

        // 屬於哪一個檔案
        if (null != entity.getUploadFile())
        {
            DetachedCriteria detachedCriteria = criteria.createCriteria("uploadFile");

            // PK 有值，需加入為查詢條件
            if (null != entity.getUploadFile().getUploadFilePk())
            {
                detachedCriteria.add(Restrictions.idEq(entity.getUploadFile().getUploadFilePk()));
            }

            // UploadFile 其他查詢條件
            Example e = Example.create(entity.getUploadFile());
            e.enableLike(MatchMode.START);
            e.excludeZeroes();
            detachedCriteria.add(e);
        }

        // 屬於哪一個群組
        if (null != entity.getGroup())
        {
            DetachedCriteria detachedCriteria = criteria.createCriteria("group");

            // PK 有值，需加入為查詢條件
            if (null != entity.getGroup().getGroupPk())
            {
                detachedCriteria.add(Restrictions.idEq(entity.getGroup().getGroupPk()));
            }

            // Group 其他查詢條件
            Example e = Example.create(entity.getGroup());
            e.enableLike(MatchMode.START);
            e.excludeZeroes();
            detachedCriteria.add(e);
        }

        return criteria;
    }

    /* (non-Javadoc)
     * @see com.feib.soeasy.dao.PayerTempDao#addPayerTemp(java.util.List)
     */
    @Override
    public void addPayerTemp(List<PayerTemp> payerTemps) {
        this.getHibernateTemplate().saveOrUpdateAll(payerTemps);
        
    }

    /* (non-Javadoc)
     * @see com.feib.soeasy.dao.PayerTempDao#deletePayerTemp(com.feib.soeasy.model.UploadFile)
     */
    @Override
    
    public void deletePayerTemp(UploadFile uploadFile) {
        StringBuffer queryString = new StringBuffer();

        queryString.append("delete PayerTemp as pt where pt.uploadFile = ").append(uploadFile.getUploadFilePk());
        queryString.append(") ");
        
        this.getHibernateTemplate().bulkUpdate(queryString.toString());        
        
        
    }

    /* (non-Javadoc)
     * @see com.feib.soeasy.dao.PayerTempDao#getPayerTempNoConfirmByGroupPK(java.lang.Long, java.lang.String)
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<PayerTemp> getPayerTempNoConfirmByGroupPK(Long groupPk, String payerNo) {
        DetachedCriteria criteria = DetachedCriteria.forClass(this.getPersistentClass());
        criteria.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY);

       
            DetachedCriteria groupCriteria = criteria.createCriteria("group");
            groupCriteria.add(Restrictions.eq("groupPk", groupPk));
      

        if (StringUtils.isNotBlank(payerNo)) {
            criteria.add(Restrictions.eq("payerNo", payerNo));
        }

       criteria.add(Restrictions.isNull("payerStatus"));

        return this.getHibernateTemplate().findByCriteria(criteria);
    }
}
